<script setup>
import { Head, Link, usePage } from '@inertiajs/vue3'
import { onMounted, ref, computed, defineAsyncComponent } from 'vue'
import SpotlightLayout from '@/Layouts/SpotlightLayout.vue'
import ArticleLayout from '@/Components/Spotlight/ArticleLayout.vue'
import Container from '@/Components/Spotlight/Container.vue'
import CommentSection from '@/Components/Blog/CommentSection.vue'
import LikeButton from '@/Components/Features/LikeButton.vue'
import ShareButton from '@/Components/Features/ShareButton.vue'
import SeriesNavigation from '@/Components/Blog/SeriesNavigation.vue'
const EnhancedMarkdownRenderer = defineAsyncComponent(() => import('@/Components/Editor/EnhancedMarkdownRenderer.vue'))
import { setupGestures } from '@/utils/gestures'
import { ChatBubbleLeftIcon, PencilIcon, EllipsisVerticalIcon } from '@heroicons/vue/24/outline'
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
import { formatDate } from '@/Components/Spotlight/utils/formatDate.js'

const props = defineProps({
  post: {
    type: Object,
    required: true,
  },
  relatedPosts: {
    type: Array,
    default: () => [],
  },
  nextPost: {
    type: Object,
    default: null,
  },
  prevPost: {
    type: Object,
    default: null,
  },
  series: {
    type: Object,
    default: null,
  },
  seriesPosts: {
    type: Array,
    default: () => [],
  },
  prevInSeries: {
    type: Object,
    default: null,
  },
  nextInSeries: {
    type: Object,
    default: null,
  },
})

const currentUrl = ref('')

onMounted(() => {
  currentUrl.value = window.location.href

  if (typeof window !== 'undefined' && window.innerWidth < 768) {
    setupGestures(document.body, {
      onSwipeLeft: () => {
        if (props.nextPost) {
          window.location.href = route('blog.posts.show', props.nextPost.slug)
        }
      },
      onSwipeRight: () => {
        if (props.prevPost) {
          window.location.href = route('blog.posts.show', props.prevPost.slug)
        }
      },
    })
  }
})

const scrollToComments = () => {
  document.getElementById('comments')?.scrollIntoView({ behavior: 'smooth' })
}

const isJsonContent = computed(() => {
  const content = typeof props.post.content === 'string'
    ? props.post.content
    : JSON.stringify(props.post.content || '')

  return (
    (content.startsWith('{') && content.endsWith('}')) ||
    (content.startsWith('[{') && content.endsWith('}]'))
  )
})

const enableDebug = ref(false)
const toggleDebug = () => {
  enableDebug.value = !enableDebug.value
}

const isDevelopment = ref(import.meta.env ? import.meta.env.DEV : false)

const canEdit = computed(() => {
  const user = usePage().props.auth.user
  return Boolean(user)
})

const articleMeta = computed(() => ({
  title: props.post.title,
  date: props.post.published_at,
}))

const chipClass = 'inline-flex items-center gap-1.5 rounded-full border border-zinc-200 px-3 py-1 text-xs font-medium text-zinc-600 transition hover:border-primary-200 hover:text-primary-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/50 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:border-zinc-600 dark:text-zinc-300 dark:hover:border-primary-400 dark:hover:text-primary-200 dark:focus-visible:ring-primary-500/40 dark:focus-visible:ring-offset-zinc-900'

</script>

<template>
  <SpotlightLayout :title="post.title">
    <Head :title="post.title" />

    <ArticleLayout :article="articleMeta">
      <div class="space-y-6 text-sm text-zinc-500 dark:text-zinc-400">
        <div class="flex flex-wrap items-center gap-3 text-xs uppercase tracking-[0.2em] text-zinc-500 dark:text-zinc-400">
          <span>{{ post.author?.name }}</span>
          <span aria-hidden="true">•</span>
          <time :datetime="post.published_at">
            {{ formatDate(post.published_at) }}
          </time>
          <template v-if="post.category">
            <span aria-hidden="true">•</span>
            <Link
              :href="route('blog.categories.show', post.category.slug)"
              class="text-primary-600 transition hover:text-primary-500 dark:text-primary-400"
            >
              {{ post.category.name }}
            </Link>
          </template>
        </div>

        <div v-if="post.featured_image" class="overflow-hidden rounded-3xl bg-zinc-100 shadow-lg ring-1 ring-zinc-100 dark:bg-zinc-800 dark:ring-zinc-700">
          <img :src="post.featured_image" :alt="post.title" class="h-full w-full object-cover" />
        </div>

        <div class="markdown-content">
          <EnhancedMarkdownRenderer
            v-if="post.content"
            :content="post.content"
            :debug="enableDebug"
          />
          <p v-else class="rounded-2xl bg-yellow-50 p-4 text-sm text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-200">
            这篇文章暂无内容，敬请期待更新。
          </p>
          <button
            v-if="isDevelopment"
            class="mt-4 text-xs text-zinc-400 transition hover:text-zinc-600 dark:hover:text-zinc-200"
            @click="toggleDebug"
          >
            {{ enableDebug ? '关闭' : '开启' }} debug
          </button>
        </div>
      </div>
    </ArticleLayout>

    <Container outer-class="mt-20" content-class="space-y-10 sm:space-y-12 lg:space-y-14">
      <div
        v-if="series"
        class="mx-auto max-w-3xl rounded-3xl bg-zinc-50/50 p-8 dark:bg-zinc-900/50"
      >
        <SeriesNavigation
          :series="series"
          :series-posts="seriesPosts"
          :current-post-id="post.id"
          :prev-in-series="prevInSeries"
          :next-in-series="nextInSeries"
        />
      </div>

      <div
        class="mx-auto max-w-3xl rounded-3xl bg-zinc-50/50 p-6 dark:bg-zinc-900/50"
      >
        <div class="flex flex-wrap items-center gap-3">
          <template v-if="post.tags?.length">
            <Link
              v-for="tag in post.tags"
              :key="tag.id"
              :href="route('blog.tags.show', tag.slug)"
              :class="[chipClass, 'uppercase tracking-[0.18em] text-[11px]']"
            >
              {{ tag.name }}
            </Link>
          </template>

          <button
            type="button"
            :class="chipClass"
            @click="scrollToComments"
          >
            <ChatBubbleLeftIcon class="h-4 w-4" />
            评论 ({{ post.comments?.length || 0 }})
          </button>

          <ShareButton :url="currentUrl" :title="post.title" variant="inline" />

          <template v-if="$page.props.auth.user">
            <LikeButton :post="post" :class="chipClass" />
          </template>

          <div v-if="canEdit" class="relative">
            <Menu as="div" class="relative inline-block text-left">
              <MenuButton
                :class="chipClass"
              >
                <EllipsisVerticalIcon class="h-4 w-4" />
                <span>更多操作</span>
              </MenuButton>

              <transition
                enter-active-class="transition duration-100 ease-out"
                enter-from-class="transform scale-95 opacity-0"
                enter-to-class="transform scale-100 opacity-100"
                leave-active-class="transition duration-75 ease-in"
                leave-from-class="transform scale-100 opacity-100"
                leave-to-class="transform scale-95 opacity-0"
              >
                <MenuItems
                  class="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-xl bg-white shadow-lg ring-1 ring-black/5 focus:outline-none dark:bg-zinc-800 dark:ring-zinc-700"
                >
                  <div class="py-1">
                    <MenuItem v-slot="{ active }">
                      <Link
                        :href="route('author.posts.edit', post.slug)"
                        :class="[
                          active ? 'bg-zinc-50 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-100' : 'text-zinc-700 dark:text-zinc-300',
                          'flex items-center gap-2 px-4 py-2 text-sm transition'
                        ]"
                      >
                        <PencilIcon class="h-4 w-4" />
                        编辑
                      </Link>
                    </MenuItem>
                  </div>
                </MenuItems>
              </transition>
            </Menu>
          </div>
        </div>
      </div>

      <div
        id="comments"
        class="mx-auto max-w-3xl rounded-3xl bg-zinc-50/50 p-8 dark:bg-zinc-900/50"
      >
        <CommentSection :post="post" :comments="post.comments || []" />
      </div>
    </Container>
  </SpotlightLayout>
</template>

<style scoped>
.markdown-content :deep(.prose) {
  max-width: 100%;
}

.markdown-content :deep(img) {
  border-radius: 0.75rem;
}

.markdown-content :deep(pre) {
  border-radius: 0.75rem;
}

.markdown-content :deep(code) {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
}
</style>
